package order

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/controllers/pay"
	"OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UpdateOrder struct {
	beego.Controller
}

func (c *UpdateOrder) UpdateOrder() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/Order/UpdateOrder"
	var err error

	order := &User.Order{}
	log := &error2.Log{}
	mes := &error2.Mes{}

	o := orm.NewOrm()
	err = json.Unmarshal([]byte(c.GetString("order")), order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	begin, err := c.GetInt("begin", -1)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	//fmt.Println(begin)
	if begin == -1 {
		err = session2.CheckSession(c.Ctx.Request.Header["Session"], 2)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}

		_, err = o.Update(order)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	} else {

		err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		err = OrderCheck(*order, openid, order.State)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		err = UpData(order, openid)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}

		//fmt.Println(order)

	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}

func UpData(order *User.Order, openid string) (err error) {

	o := orm.NewOrm()

	sql := "update `order` set state = ? where order_id = ? "
	exec, err := o.Raw(sql, order.State, order.OrderId).Exec()
	if err != nil {
		return
	}
	num, err := exec.RowsAffected()
	if err != nil {
		return
	} else if num == 0 {
		err = fmt.Errorf("失败NUM==0")
		return
	}

	if order.State == 2 && order.Coupon.CouponId != "0" {
		err = pay.UsedCoupon(order.Coupon.CouponId, openid)
		if err != nil {
			return
		}
	}
	if order.State == 4 {
		sql = "UPDATE product_detailed set sales=sales+?  where product_id=?"
		for _, OrderCart := range order.OrderCart {
			_, err = o.Raw(sql, OrderCart.Num, OrderCart.Product.ProductId).Exec()
			if err != nil {
				return
			}
		}

		err = pay.UsedCoupon(order.Coupon.CouponId, openid)
		if err != nil {
			return
		}
	}
	return nil
}
